#include <juanmabc.h>
#define JMBC_INSIDE
#include "tcGame.h"
#include "tcTrack.h"

#define STORE ID_SMALL_STORE

static TCTrack *store[STORE];

void
tcTrackCreateContext(void)
{
	idClearStore(TCTrack, STORE, store);
}

static
void
Init(TCTrack *track)
{
	mlGenMeshes(1, &track->mesh);
}

static
void
Term(TCTrack *track)
{
	mlDeleteMeshes(1, &track->mesh);
}

void
tcGenTracks(unsigned int n, unsigned int *tracks)
{
	idGenObjects(TCTrack, STORE, store, Init, n, tracks);
}

void
tcDeleteTracks(unsigned int n, unsigned int *tracks)
{
	idDeleteObjects(store, Term, n, tracks);
}

void
tcTrackLoad(unsigned int id, unsigned int name)
{
	TCGame *game;
	TCTrack *track;
	unsigned int strings[5];

	game = tcGame();
	track = store[id];

	tlGenStrings(5, strings);
	tlStringLoad(strings[0], PACKAGE_DATADIR);
	tlStringLoad(strings[1], tlStringData(name));
	tlStringConcatPath(strings[2], 2, strings);
	tlStringLoad(strings[3], L".cmesh");
	tlStringConcat(strings[4], 2, &strings[2]);
	mlMeshLoad(track->mesh, strings[4]);
	mlMeshGenMaterials(track->mesh, strings[0]);
	mlMeshCreateGeom(track->mesh, game->race.space);
	tlStringsUnload(5, strings);
	tlDeleteStrings(5, strings);
}

void
tcTrackUnload(unsigned int id)
{
	TCTrack *track;

	track = store[id];

	mlMeshDestroyGeom(track->mesh);
	mlMeshDeleteMaterials(track->mesh);
	mlMeshUnload(track->mesh);
}

void
tcTracksUnload(unsigned int n, unsigned int *tracks)
{
	unsigned int i;

	for(i = 0; i < n; i++)
		tcTrackUnload(tracks[i]);
}

void
tcTrackFrame(unsigned int id)
{
	TCTrack *track;

	track = store[id];

	//mlMeshFrustumDraw(track->mesh, frustum);
	mlMeshDraw(track->mesh);
}
